const express = require('express');
const router = express.Router();
const { query } = require('../config/database');

// 获取banner轮播图
router.get('/banner', async (req, res) => {
  try {
    const bannerQuery = `
      SELECT 
        banner_id as id,
        img_url as imgUrl,
        href_url as hrefUrl,
        banner_type as type
      FROM sys_banner 
      ORDER BY banner_id ASC
    `;
    
    const bannerData = await query(bannerQuery);
    
    res.json({
      code: '1',
      msg: '操作成功',
      result: bannerData
    });
  } catch (error) {
    console.error('获取banner失败:', error);
    res.json({
      code: '0',
      msg: '获取banner失败',
      result: null
    });
  }
});

// 获取新鲜好物
router.get('/new', async (req, res) => {
  try {
    // 查询最新商品，按商品编号倒序，限制4条
    const newGoodsQuery = `
      SELECT 
        g.goods_id as id,
        g.goods_name as name,
        g.goods_desc as \`desc\`,
        g.goods_price as price,
        g.goods_picture as picture,
        g.goods_orderNum as orderNum
      FROM sys_goods g
      ORDER BY g.goods_id DESC
      LIMIT 4
    `;
    
    const newGoods = await query(newGoodsQuery);
    
    res.json({
      code: '1',
      msg: '操作成功',
      result: newGoods
    });
  } catch (error) {
    console.error('获取新鲜好物失败:', error);
    res.status(500).json({
      code: '0',
      msg: '获取新鲜好物失败',
      result: null
    });
  }
});

// 获取热销商品（相关商品推荐）
router.get('/goods/hot', async (req, res) => {
  console.log('=== /goods/hot 接口被调用 ===');
  console.log('请求参数:', req.query);
  try {
    const { id, type, limit = 3 } = req.query;
    
    // 先测试数据库连接和表结构
    const testQuery = 'SHOW TABLES LIKE "sys_goods"';
    const tableExists = await query(testQuery);
    console.log('sys_goods表是否存在:', tableExists);
    
    if (tableExists.length === 0) {
      // 如果sys_goods表不存在，返回模拟数据
      const mockData = [
        {
          id: 1,
          name: '热销商品1',
          desc: '这是一个热销商品',
          price: '99.00',
          picture: 'https://example.com/pic1.jpg',
          orderNum: 100
        },
        {
          id: 2,
          name: '热销商品2',
          desc: '这是另一个热销商品',
          price: '199.00',
          picture: 'https://example.com/pic2.jpg',
          orderNum: 90
        }
      ];
      
      res.json({
        code: '1',
        msg: '操作成功（模拟数据）',
        result: mockData.slice(0, parseInt(limit))
      });
      return;
    }
    
    let hotGoodsQuery;
    let queryParams = [];
    
    if (type === '1') {
      // 24小时热销榜
      hotGoodsQuery = `
        SELECT 
          g.goods_id as id,
          g.goods_name as name,
          g.goods_desc as \`desc\`,
          g.goods_price as price,
          g.goods_picture as picture,
          g.goods_orderNum as orderNum
        FROM sys_goods g
        WHERE g.goods_id != ?
        ORDER BY g.goods_orderNum DESC
        LIMIT ?
      `;
      queryParams = [id || 0, parseInt(limit)];
    } else if (type === '2') {
      // 周热销榜
      hotGoodsQuery = `
        SELECT 
          g.goods_id as id,
          g.goods_name as name,
          g.goods_desc as \`desc\`,
          g.goods_price as price,
          g.goods_picture as picture,
          g.goods_orderNum as orderNum
        FROM sys_goods g
        WHERE g.goods_id != ?
        ORDER BY g.goods_orderNum DESC
        LIMIT ?
      `;
      queryParams = [id || 0, parseInt(limit)];
    } else if (type === '3') {
      // 总热销榜
      hotGoodsQuery = `
        SELECT 
          g.goods_id as id,
          g.goods_name as name,
          g.goods_desc as \`desc\`,
          g.goods_price as price,
          g.goods_picture as picture,
          g.goods_orderNum as orderNum
        FROM sys_goods g
        WHERE g.goods_id != ?
        ORDER BY g.goods_orderNum DESC
        LIMIT ?
      `;
      queryParams = [id || 0, parseInt(limit)];
    } else {
      // 默认推荐相关商品
      hotGoodsQuery = `
        SELECT 
          g.goods_id as id,
          g.goods_name as name,
          g.goods_desc as \`desc\`,
          g.goods_price as price,
          g.goods_picture as picture,
          g.goods_orderNum as orderNum
        FROM sys_goods g
        WHERE g.goods_id != ?
        ORDER BY RAND()
        LIMIT ?
      `;
      queryParams = [id || 0, parseInt(limit)];
    }
    
    const hotGoods = await query(hotGoodsQuery, queryParams);
    
    res.json({
      code: '1',
      msg: '操作成功',
      result: hotGoods
    });
  } catch (error) {
    console.error('获取热门商品失败:', error);
    res.status(500).json({
      code: '0',
      msg: '获取热门商品失败',
      result: null
    });
  }
});

// 获取人气推荐
router.get('/hot', async (req, res) => {
  try {
    // 查询热门推荐数据
    const sql = `
      SELECT 
        h.hot_id as id,
        h.hot_pictures_id as picture,
        h.hot_title as title,
        h.hot_alt as alt
      FROM sys_hot h
      ORDER BY h.hot_id ASC
    `;
    
    const hotData = await query(sql);
    
    res.json({
      code: '1',
      msg: '操作成功',
      result: hotData
    });
  } catch (error) {
    console.error('获取人气推荐失败:', error);
    res.status(500).json({
      code: '0',
      msg: '获取人气推荐失败',
      result: null
    });
  }
});

// 获取头部分类导航
router.get('/category/head', async (req, res) => {
  try {
    // 查询所有一级分类
    const categoryQuery = `
      SELECT 
        c.category_id as id,
        c.category_name as name,
        c.category_icon as picture
      FROM sys_category c 
      WHERE c.category_parent IS NULL OR c.category_parent = 0
      ORDER BY c.category_id ASC
      LIMIT 10
    `;
    
    const categories = await query(categoryQuery);
    
    // 为每个分类添加children和goods数据
    for (let category of categories) {
      // 查询子分类
      const childrenQuery = `
        SELECT 
          c.category_id as id,
          c.category_name as name
        FROM sys_category c
        WHERE c.category_parent = ?
        ORDER BY c.category_id ASC
        LIMIT 10
      `;
      
      const children = await query(childrenQuery, [category.id]);
      category.children = children;
      
      // 查询商品
      const goodsQuery = `
        SELECT 
          g.goods_id as id,
          g.goods_name as name,
          g.goods_desc as \`desc\`,
          g.goods_price as price,
          g.goods_picture as picture
        FROM sys_goods g
        ORDER BY g.goods_orderNum DESC
        LIMIT 10
      `;
      
      const goods = await query(goodsQuery);
      category.goods = goods;
    }
    
    res.json({
      code: '1',
      msg: '获取头部分类成功',
      result: categories
    });
  } catch (error) {
    console.error('获取头部分类失败:', error);
    res.json({
      code: '0',
      msg: '获取头部分类失败',
      result: null
    });
  }
});

// 获取所有商品模块
router.get('/goods', async (req, res) => {
  try {
    // 查询商品分类和对应的商品
    const categorySql = `
      SELECT 
        c.category_id as id,
        c.category_name as name,
        c.category_icon as picture
      FROM sys_category c
      WHERE c.category_parent IS NULL OR c.category_parent = 0
      ORDER BY c.category_id ASC
      LIMIT 5
    `;
    
    const categories = await query(categorySql);
    
    // 为每个分类查询商品和子分类
    for (let category of categories) {
      // 添加固定的saleInfo
      category.saleInfo = "全场3件8折";
      
      // 查询子分类（模拟数据）
      const childrenQuery = `
        SELECT 
          c.category_id as id,
          c.category_name as name,
          2 as layer,
          NULL as parent
        FROM sys_category c
        WHERE c.category_parent = ?
        ORDER BY c.category_id ASC
        LIMIT 7
      `;
      
      const children = await query(childrenQuery, [category.id]);
      category.children = children;
      
      // 查询商品
      const goodsQuery = `
        SELECT 
          g.goods_id as id,
          g.goods_name as name,
          g.goods_desc as \`desc\`,
          g.goods_price as price,
          g.goods_picture as picture,
          g.goods_orderNum as orderNum
        FROM sys_goods g
        ORDER BY g.goods_orderNum DESC
        LIMIT 8
      `;
      
      const goods = await query(goodsQuery);
      category.goods = goods;
    }
    
    res.json({
      code: '1',
      msg: '操作成功',
      result: categories
    });
  } catch (error) {
    console.error('获取商品模块失败:', error);
    res.status(500).json({
      code: '0',
      msg: '获取商品模块失败',
      result: null
    });
  }
});

module.exports = router;